﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FairyGUI;
using System.Reflection;
using System.IO;
using UnityEngine;

namespace Model
{
    [GameUIView(UIViewType.CardMake)]
    public class DeckMakeView : GameUIView
    {
        public override string PackageName { get; set; } = "Battle";

        public override string ViewName { get; set; } = "CardMake";

        List<BattleCard> Cards;

        GList GCards,CardComponents;

        BattleCard ShowCard;

        public override void Init()
        {
            Cards = BattleCardConfig.Single.cards.ToList();
            GCards = MainView.GetChild("n2").asList;
            GCards.onClickItem.Add(CardItemClick);
            CardComponents = MainView.GetChild("n3").asList;
            MainView.GetChild("n5").onClick.Add(() =>
            {
                SaveTxt("/Res/Config/BattleCard.txt");
            });
            MainView.GetChild("n10").onClick.Add(CreatNew);
            MainView.GetChild("n12").onClick.Add(CreatComponent);
            MainView.GetChild("n14").onClick.Add(AddComSp);
            MainView.GetChild("n15").onClick.Add(Delete);
            Fresh();
        }

        void Delete()
        {
            Cards.Remove(ShowCard);
            ShowCard = null;
            Fresh();
        }

        void AddComSp()
        {
            switch (MainView.GetChild("n13").asComboBox.selectedIndex)
            {
                case -1:
                    break;
                case 0:
                    ShowCard.AddComponent<Features_StableComponent>();
                    break;
            }
        }

        void CreatComponent()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            try
            {
                object o = assembly.CreateInstance("Model." + MainView.GetChild("n11").text);
                MethodInfo method = ShowCard.GetType().GetMethod("AddComponent", new Type[] { });
                method = method.MakeGenericMethod(o.GetType());
                method.Invoke(ShowCard, null);
                Fresh();
            }
            catch 
            {
                Log.Error("Failed");
            }
        }

        void CreatNew()
        {
            BattleCard card = new BattleCard();
            card.Id = Cards.Count + 100;
            card.AddComponent<SetAsPowerComponent>();
            Cards.Add(card);
            switch (MainView.GetChild("n9").asComboBox.selectedIndex)
            {
                case -1:
                    Cards.Remove(card);
                    break;
                case 0:
                    card.AddComponent<CharactorCardComponent>();
                    break;
                case 1:
                    card.AddComponent<SpellCardComponent>();
                    break;
                case 2:
                    card.AddComponent<TrapCardSetComponent>();
                    break;                   
            }
            Fresh();
        }

        void CardItemClick(EventContext eventContext)
        {
            SetShowCard(((eventContext.data as GComponent)).data as BattleCard);
        }

        void SetShowCard(BattleCard card)
        {
            if (card == null) return;
            ShowCard = card;
            CardComponents.RemoveChildrenToPool();
            GComponent Base = CardComponents.AddItemFromPool().asCom;
            Base.GetChild("n1").text = "基础属性";
            Base.GetController("c1").selectedIndex = 0;
            ShowTypeFields(card.GetType(), card);
            foreach (var com in card.GetComponents())
            {
                GComponent g = CardComponents.AddItemFromPool().asCom;
                g.GetChild("n1").text = Shorter(com.GetType().ToString());
                g.GetChild("n1").data = com.GetType();
                g.GetController("c1").selectedIndex = 1;

                g.GetChild("n4").onClick.Set(()=>
                {
                    RemoveComponent(card,g);
                });
                ShowTypeFields(com.GetType(), com);
            }
            MainView.GetChild("n0").icon = "CardPic/" + card.InfoFlag;
        }

        void ShowTypeFields(Type type,Object o)
        {
            foreach (var t in type.GetFields())
            {
                GComponent g = CardComponents.AddItemFromPool().asCom;
                g.GetChild("n1").text = Shorter(t.ToString());
                g.GetChild("n1").data = t;
                g.GetChild("n2").text = t.GetValue(o)?.ToString();
                g.GetController("c1").selectedIndex = 2;
                g.GetChild("n4").onClick.Set(()=> {
                    EditField(g,o);
                });
            }
        }

        void SaveTxt(string path)
        {
            FileStream txt = new FileStream(Application.dataPath + path, FileMode.Create);
            StreamWriter sw = new StreamWriter(txt);
            foreach (var sk in Cards)
                sw.WriteLine(Model.MongoHelper.ToJson(sk));
            sw.Close();
            Debug.Log("保存数据成功");
        }

        void RemoveComponent(BattleCard battleCard,GComponent g)
        {
            try
            {
                for (int i = battleCard.GetComponents().Length - 1; i >= 0; i--)
                {
                    if (battleCard.GetComponents()[i].GetType() == (g.GetChild("n1").data as Type))
                    {
                        battleCard.RemoveComponent(battleCard.GetComponents()[i].GetType());
                        break;
                    }
                }
            }
            catch
            {

            }
            finally
            {
                Fresh();
            }
        }

        void EditField(GComponent g,object o)
        {
            FieldInfo fieldInfo = g.GetChild("n1").data as FieldInfo;
            string tx = MainView.GetChild("n4").text;
            Log.Debug(fieldInfo.ToString());
            if (fieldInfo.ToString().Contains("System.String"))
                fieldInfo.SetValue(o, tx);
            if (fieldInfo.ToString().Contains("System.Int32"))
                fieldInfo.SetValue(o, int.Parse(tx));
            Fresh();
        }

        string Shorter(string s)
        {
            return s.Replace("Model.", "")
                .Replace("System.String","")
                .Replace("System.Int32","")
                .Replace("CardSearchType","")
                .Replace("CharactorType","")
                ;
        }

        void Fresh()
        {
            GCards.RemoveChildrenToPool();
            foreach (var card in Cards)
            {
                GComponent g = GCards.AddItemFromPool().asCom;
                g.text = card.InfoFlag + ":" + card.CardName;
                g.data = card;
            }
            SetShowCard(ShowCard);
        }

        public override void OnEnter()
        {
           
        }
    }
}
